package com.example.mobile2021606185zhn0618;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class MyDataAdapter {
    private MySQLiteOpenHelper openHelper;
    private SQLiteDatabase database;
    public void openDB(Context context) {
        openHelper = new MySQLiteOpenHelper(context,"student.db",null,1);
        try{
            database = openHelper.getWritableDatabase();
        }catch (Exception e){
            database = openHelper.getReadableDatabase();
        }
    }
    public void closeDB() {
        if (database!=null){
            database.close();
            database=null;
        }
        if (openHelper!=null){
            openHelper.close();
            openHelper=null;
        }
    }
    public List<Users>QueryAll (Context context){
        List<Users> usersList = new ArrayList<>();
        openDB(context);
        Cursor cursor = database.query("users",null,null,null,null,null,null);
        if (cursor.moveToFirst()){
            do {
                int id=cursor.getInt(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);
                float score = cursor.getFloat(3);
                usersList.add(new Users(id, name, age, score));
            }while (cursor.moveToNext());
        }
        cursor.close();
        closeDB();
        return usersList;
    }
    public long insert(Context context,Users user){
        openDB(context);
        ContentValues values = new ContentValues();
        values.put("name",user.getName());
        values.put("age",user.getAge());
        values.put("score",user.getScore());
        long result = database.insert("users",null,values);
        closeDB();
        return result;
    }
    public int delete(Context context,int id){
        openDB(context);
        int result = database.delete("users","_id=?",new String[]{String.valueOf(id)});
        closeDB();
        return  result;
    }
    public int update(Context context,int id,Users users) {
        openDB(context);
        ContentValues values = new ContentValues();
        values.put("name", users.getName());
        values.put("age", users.getAge());
        values.put("score", users.getScore());
        int result = database.update("users", values, "_id=?", new String[]{String.valueOf(id)});
        closeDB();
        return result;
       }
    }

